//
//  AppDelegate.m
//  JiaoX
//
//  Created by jiaoxiu－004 on 14-10-8.
//  Copyright (c) 2014年 北京娇羞科技有限公司. All rights reserved.
//

#import "AppDelegate.h"
#import "JXSplashController.h"
#import <FIR/FIR.h> //导入头文件
#import <AVOSCloud/AVOSCloud.h>
#import "OauthKeys.h"
#import "WeChatUtil.h"
#import "JXNavigationController.h"
#import "CartOrderStatusController.h"
#import "TalkingData.h"
#import "TalkingDataAppCpa.h"
#import <AlipaySDK/AlipaySDK.h>
@interface AppDelegate ()<WXApiDelegate,UIAlertViewDelegate>
{
    BOOL isEnterForeground;
}
@end
static const char kRepresentedObject;
@implementation AppDelegate

- (id)init{
    if(self = [super init]){
        _scene = WXSceneSession;
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self setDefaultValues];
    AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if(JXScreenH > 480){
        myDelegate.autoSizeScaleX = JXScreenW/320;
        myDelegate.autoSizeScaleY = JXScreenH/568;
    }else{
        myDelegate.autoSizeScaleX = 1.0;
        myDelegate.autoSizeScaleY = 1.0;
    }
    myDelegate.isClearPrivacyPwd = NO;
    self.isCanLoadPic = [UserDefaultsHelper boolForKey:KEY_SHOW_PIC];
    
    
    [TalkingData sessionStarted:@"EF89A70316CE78497D2011A1456DB1DE" withChannelId:@"APPSTORE"];
    [TalkingDataAppCpa init:@"c38bd13fa0bc42c6812032e0ce510cc1" withChannelId:@"APPSTORE"];
    
    [FIR handleCrashWithKey:@"4b91ed02f330491f3d574e691cc1696e"];
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [[JXSplashController alloc]init];
    [self.window makeKeyAndVisible];
    
    
    //设置状态栏的文字颜色(前提得到Info.plist中设置UIViewControllerBasedStatusBarAppearance为NO)
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    //设置整体的导航栏的背影颜色
    [[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];
    
    
    [AVOSCloud setApplicationId:LEANCLOUD_APPID clientKey:LEANCLOUD_APPKEY];
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    
    //打开接收推送消息
    if ([UserDefaultsHelper boolForKey:KEY_PUSH_STATUS]) {
        [Utils openPush];
    }
    
    NSDictionary *userInfo =[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(userInfo){
        //程序是由推送服务器启动的
        JXLog(@"程序是由推送服务器启动的：%@",userInfo);
        [UserDefaultsHelper setObject:userInfo forKey:KEY_NOTI_PUSH_STRING];
    }
    
    //微信相关
    [WXApi registerApp:WXAPP_ID];

    return YES;
}

-(void)setDefaultValues{
    NSDictionary *defaultValues = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [NSNumber numberWithBool:NO], KEY_PWD_STATUS,
                                   [NSNumber numberWithBool:YES], KEY_SHOW_PIC,
                                   [NSNumber numberWithBool:YES], KEY_PUSH_STATUS,
                                   nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
}
/*-------------------------wx start-------------------------*/
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url{
    if([url.absoluteString hasPrefix:@"tencent"]){
        return [TencentOAuth HandleOpenURL:url];
    }
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{

    //-----------alipay start-------------
    //如果极简 SDK 不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给 SDK
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
             [self sendPayNotifyStatus:resultDic[@"resultStatus"]]; ;
            JXLog(@"result = %@   resultStatus =  %@",resultDic,resultDic[@"resultStatus"]);
        }];
    }
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    //-----------alipay end-------------
    if([url.absoluteString hasPrefix:@"tencent"]){
        return [TencentOAuth HandleOpenURL:url];
    }else if ([url.host isEqualToString:@"safepay"]){
        return YES;
    }
    return [WXApi handleOpenURL:url delegate:self];
}

-(void) onReq:(BaseReq*)req{
    JXLog(@"%@",req);
}

-(void) onResp:(BaseResp *)mResp{//微信 response
    if([mResp isKindOfClass:[SendMessageToWXResp class]]){//发送消息处理结果返回
        switch (mResp.errCode) {
            case WXSuccess://发送成功
                
                break;
            case WXErrCodeUserCancel://用户取消发送
                
                break;
            case WXErrCodeSentFail://发送失败
                
                break;
            case WXErrCodeAuthDeny://授权失败
                
                break;
            default:
                
                break;
        }
    }else if([mResp isKindOfClass:[PayResp class]]){//支付返回
        switch (mResp.errCode) {
            case WXSuccess://支付成功
                [self sendPayNotifyStatus:@"9000"];
                break;
            case WXErrCodeUserCancel://用户取消支付
                [self sendPayNotifyStatus:@"6001"];
                break;
            default://支付失败
                [self sendPayNotifyStatus:@"4000"];
                break;
        }
    }else if([mResp isKindOfClass:[SendAuthResp class]]){
        switch (mResp.errCode) {
            case WXSuccess://登录授权成功
                [WeChatUtil getWxResqParams:mResp];
                break;
            case WXErrCodeUserCancel://用户取消授权
                
                break;
            case WXErrCodeAuthDeny://授权失败
                
                break;
            default:
                
                break;
        }
    }
}

/**
 *  发送支付结果通知
 *
 *  @param resultCode
 */
-(void)sendPayNotifyStatus:(NSString *)resultCode{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"pay_status" object:resultCode];
}

/*-------------------------wx end-------------------------*/

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    NSString *deviceTokenStr = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                 stringByReplacingOccurrencesOfString: @">" withString: @""]
                                stringByReplacingOccurrencesOfString: @" " withString: @""];
    [UserDefaultsHelper setObject:deviceTokenStr forKey:KEY_DEVICE_TOKEN];
    [currentInstallation setDeviceTokenFromData:deviceToken];
    [currentInstallation saveInBackground];
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    JXLog(@"推送内容：%@",userInfo);
    //isEnterForeground==true的话，这个代表是app在后台运行，用户点击了推送消息，进行相关处理
    [[NSNotificationCenter defaultCenter] postNotificationName:KEY_NOTI_PUSH_STRING object:[NSNumber numberWithBool:isEnterForeground] userInfo:userInfo];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex) {
        NSDictionary *userInfo = objc_getAssociatedObject(alertView,&kRepresentedObject);
        [[NSNotificationCenter defaultCenter] postNotificationName:KEY_NOTI_PUSH_STRING object:userInfo];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the bpackground to the inactive state; here you can undo many of the changes made on entering the background.
    isEnterForeground = YES;
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    isEnterForeground = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"applicationDidBecomeActive" object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "me.jiaoxiu.mobile.JiaoX" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"JiaoX" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"JiaoX.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


@end
